<template>
    <div id="chat" style="height: 93vh;" class="flex-1 py-5 sm:px-6 lg:px-5 flex flex-col ml-64">
        <div class="flex-1 bg-white shadow-md rounded-lg p-4 overflow-y-auto" ref="chatArea">
            <!-- 聊天消息区域 -->
            <div class="flex flex-col space-y-4">
                <div v-for="(message, index) in chatMessages" :key="index"
                    :class="{ 'flex justify-start': !message.isUser, 'flex justify-end': message.isUser }">
                    <div :class="{ 'bg-gray-200': !message.isUser, 'bg-blue-100': message.isUser }"
                        class="p-3 rounded-lg max-w-xl">
                        <!--展示消息内容-->
                        <div v-html="processContent(message.content)"></div>
                        <!-- 遍历 docRefs 展示图片 -->
                        <div v-if="message.docRefs != null && message.docRefs.length > 0" class="mt-2">
                            <div v-for="(ref, refIndex) in message.docRefs" :key="refIndex" class="flex space-x-4">
                                <div v-if="ref.refUrls != null && ref.refUrls.length > 0"
                                    v-for="(url, urlIndex) in ref.refUrls" :key="urlIndex">
                                    <img :src="url" alt="Reference Image"
                                        class="mt-1 w-20 h-20 object-cover cursor-pointer transform transition-transform hover:scale-105"
                                        @click="openFullImage(url)">
                                    <p class="text-center text-sm mt-1">{{ ref.index }}</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <!-- 模态框用于显示全图 -->
        <div v-if="showFullImage" class="fixed inset-0 bg-black bg-opacity-50 flex justify-center items-center">
            <div class="bg-white p-4 rounded-lg relative">
                <img :src="fullImageUrl" alt="Full Image" class="max-w-full max-h-full">
                <button @click="closeFullImage" class="absolute top-2 right-2">
                    <svg t="1744171280645" class="icon" viewBox="0 0 1066 1024" version="1.1"
                        xmlns="http://www.w3.org/2000/svg" p-id="1242" width="16" height="16">
                        <path
                            d="M789.674667 842.922667L181.248 234.496A37.973333 37.973333 0 0 1 234.922667 180.906667l608.512 608.426666a37.973333 37.973333 0 1 1-53.717334 53.76l-0.042666-0.128z"
                            p-id="1243" fill="#bfbfbf"></path>
                        <path
                            d="M789.76 180.906667a37.973333 37.973333 0 0 1 53.674667 53.674666L235.008 843.093333a37.973333 37.973333 0 1 1-53.674667-53.717333l608.426667-608.426667z"
                            p-id="1244" fill="#bfbfbf"></path>
                    </svg>
                </button>
            </div>
        </div>
        <!-- 输入框和发送按钮 -->
        <div class="mt-4 flex space-x-4">
            <input v-model="inputMessage" type="text" placeholder="输入你的问题..."
                class="flex-1 border border-gray-300 rounded-md p-3 focus:outline-none focus:border-blue-500"
                @keydown.enter="sendMessage">
            <button @click="sendMessage"
                class="bg-blue-500 text-white px-4 py-3 rounded-md hover:bg-blue-600 focus:outline-none">
                发送
            </button>
        </div>
    </div>
</template>

<script setup>
import { useChatApi } from "../../../api/chat"
import { useAdminInfoStore } from '../../../store';
import { ref } from 'vue'
import MarkdownIt from 'markdown-it';

const md = new MarkdownIt();
// 控制全图模态框的显示和隐藏
const showFullImage = ref(false);
const fullImageUrl = ref('');
const chatArea = ref(null)
// 加载标志
const isLoading = ref(false);
const openFullImage = (url) => {
    fullImageUrl.value = url;
    showFullImage.value = true;
};
// 实例化容器
const adminInfo = useAdminInfoStore();

const closeFullImage = () => {
    showFullImage.value = false;
};

const chatApi = new useChatApi();
const inputMessage = ref('');
const chatMessages = adminInfo.getChatMessages;

// 自动滚动到结尾
const scrollAuto = () => {
    if (chatArea.value) {
        chatArea.value.scrollTop = chatArea.value.scrollHeight;
    }
}

// 处理内容
const processContent = (content) => {
    // 替换 <ref>[num]</ref> 为 <sup>[num]</sup>
    let newContent = content.replace(/<ref>\[(\d+)\]<\/ref>/g, '【$1】');
    newContent = md.render(newContent);
    return newContent;
};

const sendMessage = () => {
    // 防止空白输入
    if (inputMessage.value.trim() === '') return;
    // 添加用户消息
    chatMessages.push({ content: inputMessage.value, isUser: true, docRefs: [] });
    isLoading.value = true;
    scrollAuto();
    let newMessage = {
        content: "正在加载中···",
        isUser: false,
        docRefs: {},
    }
    chatMessages.push(newMessage);
    chatApi.fullTextChat(inputMessage.value).then(response => {
        if (response.data.code == 1) {
            adminInfo.setChatSessionId(response.data.data.chatSessionId);
            console.log(adminInfo.getChatSessionId);
            // 添加响应消息
            chatMessages[chatMessages.length - 1] = {
                content: response.data.data.answer,
                isUser: false,
                docRefs: response.data.data.references == null ? null : response.data.data.references.map(ref => ({
                    index: ref.index,
                    refUrls: ref.refUrls,
                }))
            }
            scrollAuto();
        } else {
            ElMessage.error(response.data.message)
        }
    }).catch(error => {
        console.error(error);
        chatMessages[chatMessages.length - 1] = {
            content: '请求出错，请稍后重试。',
            isUser: false,
            docRefs: []
        };
        scrollAuto();
    }).finally(() => {
        isLoading.value = false;
    })
    // 清空输入框
    inputMessage.value = '';
}
</script>

<style scoped></style>